﻿Imports System.Runtime.CompilerServices
Imports System.Text

Public Module 发送命令到cad封装

    Public Function SendCmd2Acad(ByVal cadWinHWND As String, ByVal scriptcmd As List(Of String)) As Integer
        Dim cmdStr As New StringBuilder, rtn As Integer
        scriptcmd.ForEach(Function(ByVal c As String) cmdStr.Append((c & vbCr)))
        Dim hwnd As New IntPtr(CInt(cadWinHWND))
        '窗口置顶
        Dim data As String = cmdStr.ToString() & ChrW(0)
        Dim cds As New COPYDATASTRUCT With {.lpData = Marshal.StringToCoTaskMemAuto(data), .cbData = data.Length * Marshal.SystemDefaultCharSize, .dwData = New IntPtr(1)}
        rtn = SendMessageW(hwnd, &H4A, IntPtr.Zero, cds)
        ShowWindow(hwnd, SW_SHOWNORMAL)
        SetForegroundWindow(hwnd)
        BringWindowToTop(hwnd)
        Return rtn
    End Function

    <DllImport("user32.dll")>
    Private Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
    End Function

    <DllImport("user32.dll")>
    Private Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByRef lParam As COPYDATASTRUCT) As IntPtr
    End Function

    <DllImport("user32")>
    Public Function BringWindowToTop(ByVal hwnd As IntPtr) As Integer
    End Function

    <DllImport("user32")>
    Public Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Integer
    End Function

    Public Const SW_MAX As Integer = 10
    Public Const SW_MAXIMIZE As Integer = 3
    Public Const SW_MINIMIZE As Integer = 6
    Public Const SW_SHOWNORMAL As Integer = 1

End Module

Public Structure COPYDATASTRUCT
    Public dwData As IntPtr
    Public cbData As Integer
    Public lpData As IntPtr
End Structure
